package cn.com.miao.lynx.common.base.service;

import cn.com.miao.lynx.common.base.model.TreeModel;
import cn.com.miao.lynx.common.core.constant.CommonConstant;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import java.io.Serializable;

/**
 * TreeService
 *
 * @title: TreeService
 * @description:
 * @author: dengmiao
 * @create: 2019-12-31 11:36
 **/
public interface TreeService<Entity extends TreeModel<Entity, ID>, ID extends Serializable> extends BaseService<Entity, ID> {

    @Override
    default Entity create(Entity entity) {
        Class<ID> clazz = (Class<ID>) getClazz(1);
        ID parentId = entity.getParentId();
        ID rootPid = Convert.convert(clazz, CommonConstant.System.ROOT_PID);
        String parentIds = entity.getParentIds();
        if (ObjectUtil.isEmpty(parentIds)) {
            if (ObjectUtil.isNull(parentId) || parentId.equals(rootPid)) {
                entity.setParentId(rootPid);
                entity.setParentIds(rootPid + StrUtil.COMMA);
            }
            else {
                Entity parent = retrieve(parentId).get();
                entity.setParentIds(parent.getParentIds() + parent.getId() + StrUtil.COMMA);
            }
        }
        return getRepository().save(entity);
    }
}
